package time_util

import (
	"database/sql/driver"
	"github.com/pkg/errors"
	"time"
	"trpg-common/logger"
)

type Time time.Time

const (
	timeFormat = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
	*t = Time(now)
	return
}

func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormat)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, timeFormat)
	b = append(b, '"')
	return b, nil
}

func (j *Time) Scan(value interface{}) error {
	*j = Time(value.(time.Time))
	return nil
}

// 实现 driver.Valuer 接口，Value 返回 json value
func (j Time) Value() (driver.Value, error) {
	return time.Time(j), nil
}

func (t Time) Second() int {
	t2 := time.Time(t)
	return t2.Second()
}

func (t Time) ToString() string {
	json, err := t.MarshalJSON()
	if err != nil {
		logger.Logger.Panicf("%+v", errors.Wrap(err, "error in convert time to string"))
	}
	s := string(json)
	return s[1 : len(s)-1]
}

func Now() *Time {
	t := Time(time.Now())
	return &t
}

func UnixToTime(data int64) time.Time {
	return time.Unix(data/1000, 0)
}

func ToTimeUtilTime(timeRaw time.Time) Time {
	return Time(timeRaw)
}
